package com.ff.javamonkey.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.util.Log;

import com.ff.javamonkey.socket.ClientConnect;

public class IOUtils {
	// Debugging
	private static final String TAG = "IOUtils";

	public static final int IO_BUFFER_SIZE = 4 * 1024;
	public static long copied;
	
	private IOUtils() {
		// utility class
	}
	
	public static long copy(InputStream in, OutputStream out, long length, ClientConnect client) throws IOException {
		copied = 0;
		int currentLength = 0;
		if (out == null)
			Log.i(TAG, "Are you crazy?");
		int len = (int) Math.min(length, IO_BUFFER_SIZE);
		byte[] buffer = new byte[len];
		while (length > 0) {
			len = in.read(buffer, 0, len);
			if (len < 0) {
				break;
			}
			if (out != null) {
				out.write(buffer, 0, len);
			}
			Log.i(TAG, "Heavy Debugging Mode on: " + buffer.length + " - " + len + " - " + copied + " - " + length);
			copied += len;
			currentLength += len;
			client.setReadStatus(currentLength);
			length -= len;
			len = (int) Math.min(length, IO_BUFFER_SIZE);
		}
		return copied;
	}
}
